package com.etc.classdemo;

import java.lang.reflect.InvocationTargetException;

/**
 * 如何得到一个Class类型的对象呢?
 * 1. 对象名.getClass()
 * 2. Class.forName("包名+类名")
 * 3.类名.class
 */
public class TestPerson {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        //1构造一个对象
        Person person = new Person(1,"小a");
        System.out.println(person);

        //2构造一个对象
        Class<Person> personClass = Person.class;
        Person person1 = personClass.newInstance();
        person1.setId(2);
        person1.setName("小z");
        System.out.println(person1);


//        //构造构造一个对象 借助 Class对对象
//        Class personClass = person.getClass();
//
//        //得到一个Object
//        Object o = personClass.newInstance();
//
//        System.out.println(o);

        Object insance1 = getInsance1(Person.class);
        Object insance2 = getInsance2(Person.class);
        System.out.println(insance1);
        System.out.println(insance2);

    }

    /**
     * 代码目的就是创建一个类型对象，但是程序编译期不确定要创建的是哪个类型的对象
     * 在程序运行期才能决定，这个时候Class就派上用场了.
     * @param cls
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static Object getInsance1(Class cls) throws InstantiationException, IllegalAccessException {

        Object o = cls.newInstance();
        return o;
    }

    /**
     * The call
     *  clazz.newInstance()
     *  can be replaced by
     *  clazz.getDeclaredConstructor().newInstance()
     * @param cls
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static  Object getInsance2(Class cls) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        Object o = cls.getDeclaredConstructor().newInstance();
        return o;
    }
}
